<script setup>
import {
  computed,
  inject,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch,
  watchEffect,
} from 'vue'
import {
  deleteIndexData,
  deleteIndexEvaluate,
  queryOperation,
} from '@api/city-index'
import AddDataItem from '@v/data-converge/indicator-manage/add/AddDataItem.vue'
import { Message, Message as ElMessage } from 'element-ui'
import { cloneDeep } from 'lodash'
import { v4 } from 'uuid'
import { debounce } from '@/utils/radash'

const {
  changeIndexInfo,
  addIndexData,
  addIndexEvaluate,
  changeIndexEvaluate,
  changeIndexData,
  deleteDataItem,
  deleteEvaluateIndex,
  getIndexFormula,
} = inject('link')

const cursorActive = ref(-1)

const isCursorShow = ref(false)

const currentDataItemIndex = ref(-1)

const editDataItem = ref(null)
const editDataItemIndex = ref(-1)

const addDataItemRef = ref()

const dataItemList = ref([])

const visible = ref(false)

// let clickTimer
// let clickCount = 0

const handleClosed = () => {
  visible.value = false
  addDataItemRef.value.inputData({
    dataItem: '',
    unit: '',
  })
}

const handleConfirm = (data) => {
  if (editDataItem.value) {
    Object.assign(editDataItem.value, data)
    changeIndexData(editDataItemIndex.value, 'dataItem', data.dataItem)
    changeIndexData(editDataItemIndex.value, 'unit', data.unit)
    editDataItem.value = null
    visible.value = false
    editDataItemIndex.value = -1
    return
  }
  const pkid = v4().replaceAll('-', '')
  dataItemList.value.push({
    ...data,
    pkid,
  })
  addIndexData({
    ...data,
    pkid,
  })
  visible.value = false
}

const props = defineProps({
  indexInfo: {
    type: Object,
    default: () => {},
  },
  show: {
    type: Boolean,
    default: false,
  },
  disabled: Boolean,
})

const infoForm = reactive({
  indexParaphrase: '',
  indexUnit: '',
  indexType: '',
})

const formula = ref([])

const normData = ref([])

const operationData = ref([])

// watch(
//   () => props.indexInfo.pkid,
//   (val) => {
//     if (!val) {
//       const obj = {
//         indexParaphrase: '',
//         indexUnit: '',
//         indexType: '',
//       }
//       Object.assign(infoForm, obj)
//       formula.value = []
//       normData.value = []
//       dataItemList.value = []
//       cursorActive.value = -1
//       isCursorShow.value = false
//     } else {
//       Object.assign(infoForm, props.indexInfo.indexInformationRel)
//       normData.value = cloneDeep(props.indexInfo.indexEvaluateRels)
//       dataItemList.value = cloneDeep(props.indexInfo.indexDataRels)
//       formula.value = cloneDeep(props.indexInfo.indexFormulaRelList)
//       cursorActive.value = formula.value.length - 1
//       isCursorShow.value = false
//     }
//   }
// )

let oldId = 'initTempId'

watchEffect(() => {
  let id
  if (Object.prototype.hasOwnProperty.call(props.indexInfo, 'pkid')) {
    id = props.indexInfo.pkid
  } else {
    id = props.indexInfo.tempId
  }
  // if (oldId === id) return
  // oldId = id
  if (!id) {
    const obj = {
      indexParaphrase: '',
      indexUnit: '',
      indexType: '',
    }
    Object.assign(infoForm, obj)
    formula.value = []
    normData.value = []
    dataItemList.value = []
    cursorActive.value = -1
    isCursorShow.value = false
  } else {
    Object.assign(infoForm, props.indexInfo.indexInformationRel)
    normData.value = cloneDeep(props.indexInfo.indexEvaluateRels)
    dataItemList.value = cloneDeep(props.indexInfo.indexDataRels)
    formula.value = cloneDeep(props.indexInfo.indexFormulaRelList)
    cursorActive.value = formula.value.length - 1
    isCursorShow.value = false
  }
})

const typeOptions = [
  {
    label: '区间型',
    value: '区间型',
  },
  {
    label: '底线型',
    value: '底线型',
  },
  {
    label: '目标型',
    value: '目标型',
  },
  {
    label: '普查型',
    value: '普查型',
  },
]

const getOperation = () => {
  queryOperation().then((res) => {
    if (res.success) {
      operationData.value = res.data
    }
  })
}

onMounted(() => {
  getOperation()
})

const handleChangeInfo = (key) => {
  changeIndexInfo(key, infoForm[key])
}

const handleChangeTable = (index, key, value) => {
  changeIndexEvaluate(index, key, value)
}

const handleAddDataItem = () => {
  if (props.disabled) return
  editDataItem.value = null
  visible.value = true
}

const handleClickDataItem = (index) => {
  if (props.disabled) return
  // clickCount++
  // if (clickCount === 1) {
  //   clickTimer = setTimeout(() => {
  currentDataItemIndex.value = index
  // clickCount = 0
  //   }, 200)
  // }
}

const handleMouseLeave = () => {
  // console.log(666)
  currentDataItemIndex.value = -1
}

const handleDbClick = (data) => {
  if (props.disabled) return
  // clearTimeout(clickTimer)
  // clickCount = 0

  const item = {
    type: 'dataItem',
    refId: data.pkid,
  }
  changeFormula(item)
  cursorActive.value = cursorActive.value + 1
}

const changeFormula = (item) => {
  const len = formula.value.length
  if (cursorActive.value === -1) {
    formula.value.unshift(item)
    getIndexFormula().unshift({
      ...item,
    })
  } else if (cursorActive.value === len - 1) {
    formula.value.push(item)
    getIndexFormula().push({
      ...item,
    })
  } else {
    formula.value.splice(cursorActive.value + 1, 0, item)
    getIndexFormula().splice(cursorActive.value + 1, 0, {
      ...item,
    })
  }
  getIndexFormula().map((item, index) => {
    item.orderIndex = index + 1
  })
}

const getFormulaText = (item) => {
  if (item.type === 'operate') {
    const find = operationData.value.find((val) => val.pkid === item.refId)
    if (find) {
      return find.operate
    } else {
      return ''
    }
  } else if (item.type === 'input') {
    return item.value
  } else {
    const find = dataItemList.value.find((val) => val.pkid === item.refId)
    if (find) {
      return `${find.dataItem}（${find.unit}）`
    } else {
      return ''
    }
  }
}

const handleDblClick = (item) => {
  if (props.disabled) return
  const value = {
    type: 'operate',
    refId: item.pkid,
  }
  changeFormula(value)
  cursorActive.value = cursorActive.value + 1
}

const handleClickCursor = (index) => {
  if (props.disabled) return
  cursorActive.value = index
}

const handleAddNormal = () => {
  if (!infoForm.indexType) {
    ElMessage.warning('请选择指标类型后重试！')
    return
  }
  normData.value.push({
    evaluateResult: '',
    moreThan: null,
    lessThan: null,
  })
  addIndexEvaluate({
    evaluateResult: '',
    moreThan: null,
    lessThan: null,
  })
}

const handleEditDataItem = (data, index) => {
  editDataItem.value = data
  editDataItemIndex.value = index
  addDataItemRef.value.inputData(data)
  visible.value = true
}

const handleCursorShow = () => {
  isCursorShow.value = true
}

const changeCursorShow = () => {
  if (props.disabled) return
  isCursorShow.value = false
}

const handleKeyUp = (e) => {
  if (props.disabled) return
  if (e.keyCode == 8) {
    // 删除
    if (isCursorShow.value) {
      const index = cursorActive.value
      if (index > -1) {
        formula.value.splice(index, 1)
        getIndexFormula().splice(index, 1)
        cursorActive.value = cursorActive.value - 1
        getIndexFormula().map((item, index) => {
          item.orderIndex = index + 1
        })
      }
    }
  } else if (e.keyCode == 39) {
    // 光标右移
    if (isCursorShow.value) {
      const len = formula.value.length
      if (cursorActive.value < len - 1) {
        cursorActive.value = cursorActive.value + 1
      }
    }
  } else if (e.keyCode == 37) {
    // 光标左移
    if (isCursorShow.value) {
      if (cursorActive.value > -1) {
        cursorActive.value = cursorActive.value - 1
      }
    }
  } else {
    // 数字
    // if (isCursorShow.value) {
    //   const key = e.key
    //   if (/^\d+$/.test(key) || key === '.') {
    //     handleInputNumber(e)
    //   }
    // }
  }
}

const handleInputNumber = (e) => {
  if (props.disabled) return
  const arr = formula.value
  const index = cursorActive.value
  const activeValue = arr[index]

  if (activeValue && activeValue.type === 'input') {
    activeValue.value += e.key
    getIndexFormula()[index].value += e.key
  } else {
    const item = {
      type: 'input',
      value: e.key,
    }
    changeFormula(item)
    cursorActive.value = cursorActive.value + 1
  }
}

onMounted(() => {
  window.addEventListener('click', changeCursorShow)
  window.addEventListener('keyup', handleKeyUp)
})

onBeforeUnmount(() => {
  window.removeEventListener('click', changeCursorShow)
  window.removeEventListener('keyup', handleKeyUp)
})

const delNode = (node) => {
  if (node.indexId) {
    // 调用接口
    deleteIndexData(node.pkid).then((res) => {
      if (res.success) {
        Message.success('删除数据项成功！')
        dataItemList.value = dataItemList.value.filter(
          (item) => item.pkid !== node.pkid
        )
        deleteDataItem(node.pkid)
      }
    })
  } else {
    // 未保存就删除
    Message.success('删除数据项成功！')
    dataItemList.value = dataItemList.value.filter(
      (item) => item.pkid !== node.pkid
    )
    deleteDataItem(node.pkid)
  }
}

const deleteTableItem = (data, index) => {
  if (data.pkid) {
    deleteIndexEvaluate(data.pkid).then((res) => {
      if (res.success) {
        Message.success('删除评价标准成功！')
        normData.value.splice(index, 1)
        deleteEvaluateIndex(index)
      } else {
        Message.error(res.message)
      }
    })
  } else {
    normData.value.splice(index, 1)
    deleteEvaluateIndex(index)
  }
}
</script>

<template>
  <div class="index-detail">
    <div class="title">指标信息</div>
    <el-form :model="infoForm" label-position="top" class="index-form">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="指标释义" prop="indexParaphrase">
            <el-input
              v-model="infoForm.indexParaphrase"
              placeholder="请输入指标释义"
              @input="handleChangeInfo('indexParaphrase')"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="指标单位" prop="indexUnit">
            <el-input
              v-model="infoForm.indexUnit"
              placeholder="请输入指标单位"
              @input="handleChangeInfo('indexUnit')"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="指标类型" prop="indexType">
            <el-select
              v-model="infoForm.indexType"
              placeholder="请选择指标类型"
              @input="handleChangeInfo('indexType')"
              :disabled="disabled"
            >
              <el-option
                v-for="(item, index) in typeOptions"
                :label="item.label"
                :value="item.value"
                :key="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="title">数据项及指标计算</div>
    <div class="calc-content" @click.stop="handleCursorShow">
      <div class="left">
        <div v-show="!disabled" class="top-title">
          <div class="add-index" @click="handleAddDataItem">
            <svg-icon icon-class="addIndex" />
            <p>新增数据项</p>
          </div>
        </div>
        <div class="data-list">
          <div
            :class="['list-item']"
            v-for="(item, index) in dataItemList"
            :key="index"
            @mouseenter="handleClickDataItem(index)"
            @mouseleave="handleMouseLeave"
            @click.stop="handleDbClick(item)"
          >
            <div class="item-left">
              <svg-icon icon-class="data-item" />
              <span>{{ item.dataItem }}（{{ item.unit }}）</span>
            </div>
            <div class="item-right" v-show="currentDataItemIndex === index">
              <span>
                <svg-icon
                  icon-class="编辑"
                  @click.stop="handleEditDataItem(item, index)"
                ></svg-icon
              ></span>
              <span @click.stop>
                <el-popconfirm
                  title="确定删除该数据项吗？"
                  @confirm="delNode(item)"
                >
                  <template #reference>
                    <svg-icon icon-class="删除"></svg-icon>
                  </template>
                  <!--                <svg-icon #reference icon-class="删除"></svg-icon>-->
                </el-popconfirm></span
              >
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="top-symbol" v-show="!disabled">
          <span
            class="operate"
            v-for="item in operationData"
            :key="item.pkid"
            @click="handleDblClick(item)"
            >{{ item.operate }}</span
          >
        </div>
        <div class="bottom-formula">
          <span
            :class="[
              'cursor',
              isCursorShow && cursorActive === -1 ? 'active' : '',
            ]"
            @click="handleClickCursor(-1)"
          ></span>
          <template v-for="(item, index) in formula">
            <span class="value" :key="'formula' + index">{{
              getFormulaText(item)
            }}</span>
            <span
              :key="'cursor' + index"
              @click="handleClickCursor(index)"
              :class="[
                'cursor',
                isCursorShow && cursorActive === index ? 'active' : '',
              ]"
            ></span>
          </template>
        </div>
      </div>
    </div>
    <div class="title-content" v-show="infoForm.indexType !== '普查型'">
      <div class="title">评价标准</div>
      <div class="add-index" @click="handleAddNormal" v-show="!disabled">
        <svg-icon icon-class="addIndex" />
        <p>新增评价标准</p>
      </div>
    </div>
    <el-table
      class="norm-table"
      :data="normData"
      v-show="infoForm.indexType !== '普查型'"
    >
      <el-table-column prop="evaluateResult" label="评价结论">
        <template #default="scope">
          <el-input
            v-model="scope.row.evaluateResult"
            placeholder="请输入"
            @input="
              handleChangeTable(
                scope.$index,
                'evaluateResult',
                scope.row.evaluateResult
              )
            "
            :disabled="disabled"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="moreThan"
        label="数值高于（包含）"
        v-if="infoForm.indexType !== '底线型'"
      >
        <template #default="scope">
          <el-input
            type="number"
            v-model="scope.row.moreThan"
            placeholder="请输入"
            @input="
              handleChangeTable(scope.$index, 'moreThan', scope.row.moreThan)
            "
            :disabled="disabled"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="lessThan"
        label="数值低于（不包含）"
        v-if="infoForm.indexType !== '目标型'"
      >
        <template #default="scope">
          <el-input
            type="number"
            v-model="scope.row.lessThan"
            placeholder="请输入"
            @input="
              handleChangeTable(scope.$index, 'lessThan', scope.row.lessThan)
            "
            :disabled="disabled"
          />
        </template>
      </el-table-column>
      <el-table-column width="60px">
        <template #default="scope">
          <!--          <el-button :disabled="disabled" type="text" size="mini"-->
          <!--            >删除</el-button-->
          <!--          >-->
          <el-popconfirm
            style="margin-left: 10px"
            title="确定删除该指标体系吗？"
            @confirm="deleteTableItem(scope.row, scope.$index)"
          >
            <el-button
              :disabled="disabled"
              slot="reference"
              type="text"
              style="color: #ff125b"
            >
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <add-data-item
      :visible="visible"
      @closed="handleClosed"
      @confirm="handleConfirm"
      ref="addDataItemRef"
    />
  </div>
</template>

<style scoped lang="scss">
.index-detail {
  padding-left: 20px;
  height: 100%;
  overflow-y: auto;

  .title-content {
    width: calc(100% - 40px);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .title {
    margin-top: 16px;
    font-weight: bold;
    font-size: 14px;
    color: #4e525f;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      width: 4px;
      height: 12px;
      background: #10a6dd;
      margin-right: 4px;
    }
  }

  .add-index {
    cursor: pointer;
    margin-left: 20px;
    margin-top: 10px;
    height: 12px;
    font-weight: 400;
    font-size: 14px;
    color: #10a6dd;
    display: flex;
    align-items: center;
    p {
      margin-left: 2px;
    }
  }

  :deep(.el-form.index-form) {
    width: calc(100% - 20px);
    .el-input__inner {
      background: #f9fbff;
      border-radius: 4px;
      border: 1px solid #e1ecf5;
      width: 290px;
    }

    .el-textarea__inner {
      background: #f9fbff;
      border-radius: 4px;
      border: 1px solid #e1ecf5;
    }

    .el-form-item {
      margin-bottom: 0;
    }

    .el-form-item__label {
      padding-bottom: 0;
    }
  }

  .calc-content {
    margin-top: 13px;
    width: calc(100% - 40px);
    height: 200px;
    display: flex;

    .left {
      height: 100%;
      width: 290px;
      background: #f5f8fe;
      border: 1px solid #f3f3f9;

      .top-title {
        height: 34px;
        background: #f3f3f9;
        border: 1px solid #f3f3f9;
      }

      .data-list {
        height: calc(100% - 56px);
        overflow-y: auto;
        padding: 10px;

        .list-item {
          user-select: none;
          cursor: pointer;
          display: flex;
          height: 34px;
          align-items: center;
          justify-content: space-between;
          font-weight: 400;
          font-size: 14px;
          color: #717689;
          padding: 0 9px;

          .svg-icon {
            margin-right: 6px;
          }

          &:hover {
            background: #ffffff;
            box-shadow: 0px 0px 4px 0px rgba(225, 225, 225, 0.74);
          }

          .item-left {
            display: flex;
            align-items: center;

            svg {
              flex-shrink: 0;
            }

            span {
              // word-break: break-all;
              // text-overflow: ellipsis; // text-overflow css3的属性，当文本溢出时，显示省略号
              -webkit-line-clamp: 2; // 设置两行文字溢出
              display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
              -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
              overflow: hidden; /** 隐藏超出的内容 **/
            }
          }

          .item-right {
            display: flex;
            align-items: center;
          }
        }
      }
    }

    .right {
      flex: 1;
      border: 1px solid #f3f3f9;

      .top-symbol {
        user-select: none;
        height: 34px;
        background: #f9fbff;
        border: 1px solid #f3f3f9;
        line-height: 34px;
        .operate {
          margin-left: 26px;
          cursor: pointer;

          &:hover {
            color: #00c3ff;
          }
        }
      }

      .bottom-formula {
        padding: 12px 18px;
        display: flex;
        align-items: center;

        .cursor {
          width: 1px;
          height: 20px;
          display: inline-block;
          cursor: pointer;
          text-align: center;
          margin: 0 2px;
        }

        .cursor:hover {
          background: #10a6dd;
        }

        .cursor.active {
          animation: cursorActive 1s infinite alternate;
        }
        @keyframes cursorActive {
          0% {
            opacity: 1;
            //background: #10a6dd;
            background: #333333;
          }
          100% {
            opacity: 0;
            //background: #a5dff6;
            background: transparent;
          }
        }
      }
    }
  }

  .norm-table {
    margin-top: 13px;
    margin-bottom: 20px;
    width: calc(100% - 40px);
    border-left: 1px solid #f3f3f9;
    border-right: 1px solid #f3f3f9;
  }
}
</style>
